{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "import serial #导入模块\n",
    "portx=\"COM6\"\n",
    "#portx=\"/dev/ttyUSB0\"\n",
    "  #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200\n",
    "bps=115200\n",
    "#超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）\n",
    "timex=3\n",
    "# 打开串口，并得到串口对象\n",
    "ser=serial.Serial(portx,bps,timeout=timex)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "写总字节数: 8\n"
     ]
    }
   ],
   "source": [
    "result=ser.write(\"AT+GMR\\r\\n\".encode(\"utf-8\"))\n",
    "print(\"写总字节数:\",result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "print(ser.read())#读一个字节\n",
    "print(ser.read(10).decode(\"gbk\"))#读十个字节\n",
    "print(ser.readline().decode(\"gbk\"))#读一行\n",
    "print(ser.readlines())#读取多行，返回列表，必须匹配超时（timeout)使用\n",
    "print(ser.in_waiting)#获取输入缓冲区的剩余字节数\n",
    "print(ser.out_waiting)#获取输出缓冲区的字节数\n",
    "[参考链接](https://blog.csdn.net/xuzhexing/article/details/91043579)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AT+GMR\r",
      "\r\n",
      "AT version:1.3.0.0(Jul 14 2016 18:54:01)\r\n",
      "SDK version:2\n"
     ]
    }
   ],
   "source": [
    "#read to a str\n",
    "if ser.in_waiting:\n",
    "    str=ser.read(ser.in_waiting ).decode(\"utf-8\")\n",
    "    if(str==\"exit\"):#退出标志\n",
    "        pass\n",
    "    else:\n",
    "        print(str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[b'.0.0(5a875ba)\\r\\n', b'v1.0.0.3\\r\\n', b'Mar 13 2018 09:37:06\\r\\n', b'OK\\r\\n']"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#read to a list,wait @timex secind\n",
    "a=ser.readlines()\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "ser??\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "ser.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
